#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import request,jsonify
from authlib.jose import jwt, JoseError
from Settings.config import Config
from .error_code import error_code  # 异常代码
from functools import wraps
import threading
 
import logging

Lock = threading.Lock()

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)

"""
API接口安全
1.时间戳校验
2.签名校验
3.token校验
"""


class APISecurity(object):
    """
    功能：验证API安全
    """

    __instance = None

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            try:
                Lock.acquire()
                # double check
                if not cls.__instance:
                    cls.__instance = super(APISecurity, cls).__new__(cls, *args, **kwargs)
            finally:
                Lock.release()
        return cls.__instance

    def verify_access_token(self):
        """验证token"""
        result = False
        try:
            authorization = request.headers.get('Authorization', False) or request.headers.get('authorization', False)
            if authorization:
                authorization = authorization.split(' ')
                if authorization[0] == 'Bearer':
                    claims = jwt.decode(authorization[1], Config.SECRET_KEY)
                    claims.validate()  # 验证不通过将抛异常
                    result = claims
                else:
                    logging.error('token参数非Bearer格式。')
            else:
                logging.error('未获取到token。')
        except JoseError:
            logging.error('token无效。')  # invalid token
        finally:
            return result


